package com.samon.netty.传输;
/*
               _.---..._
           ./^         ^-._
         ./^C===.         ^\.   /\
        .|'     \\        _ ^|.^.|
   ___.--'_     ( )  .      ./ /||
  /.---^T\      ,     |     / /|||
 C'   ._`|  ._ /  __,-/    / /-,||
      \ \/    ;  /O  / _    |) )|,
       i \./^O\./_,-^/^    ,;-^,'
        \ |`--/ ..-^^      |_-^
         `|  \^-           /|:
          i.  .--         / '|.
           i   =='       /'  |\._
         _./`._        //    |.  ^-ooo.._
  _.oo../'  |  ^-.__./X/   . `|    | d
				 比克叔叔保佑
				 代码无BUG!
 */

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * jdk阻塞socket
 * 
 * @author Mr.Wu on 2018/9/15
 */
public class PlainOioServer {

	public void serve(int port) throws IOException {

		// 将服务器绑定到指定端口
		final ServerSocket socket = new ServerSocket(port);
		for (; ; ) {
			// 接受连接
			final Socket clientSocket = socket.accept();
			System.out.println("接受连接, 来自: " + clientSocket);
			// 创建一个新的线程来处理该连接
			new Thread(() -> {
				OutputStream out;
				try {
					out = clientSocket.getOutputStream();
					// 将消息写给已连接的客户端
					out.write("Hi!".getBytes(Charset.forName("UTF-8")));
					out.flush();
					clientSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						clientSocket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start(); // 启动线程
			
		}
		
	}
	
}
